package lebaidai.zktest;

import java.util.concurrent.TimeUnit;

import org.apache.zookeeper.KeeperException;

import com.lebaidai.framework.lock.DistributedSharedLock;
import com.lebaidai.framework.lock.LockZookeeperClientFactory;
import com.lebaidai.framework.lock.SharedLock;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	testDistributeSharedLock();
    }
    public static void testSharedLock(){
    	//LockZookeeperClientFactory通常是通过Spring配置注入的，此处是为了Demo的简单明了才这样写的，不建议这样写
        LockZookeeperClientFactory lzc = new LockZookeeperClientFactory();
        lzc.setZookeeperIpPort("118.192.22.167:2181");
        lzc.setBasePath("/locks/sharedLock/");
        lzc.init();
 
        SharedLock sharedLock = new SharedLock(lzc, "sharedLock1");
        try {
            if (sharedLock.acquire(100, TimeUnit.MILLISECONDS)) {
                System.out.println("sharedLock1 get");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                sharedLock.release();
                Thread.sleep(50000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
        lzc.destroy();
        System.out.println("end");
    }
    public static void testDistributeSharedLock(){
    	 final DistributedSharedLock lock = new DistributedSharedLock("/_locknode2_");
    	for (int i = 0; i < 10; i++) {
            Thread t = new Thread(new Runnable() {
                public void run() {
                   
                    try {
                        lock.acquire();
                        Thread.sleep(1000); //获得锁之后可以进行相应的处理
                        System.out.println("======获得锁后进行相应的操作======");
                        lock.release();
                        System.err.println("=============================");
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }
}
